const indexOf = require('lodash/indexOf')

const Dispatch = require('../dispatch/Dispatch')
const con = require('../../config/const')
const base = require('../base/baseObj')




// 顺序请求队列 - 继发请求队列
async function queueQuery(req, res, next, query, successArr) {
    // 返回的结果集,请求队列的长度
    const arr = [], len = query.length
    // 是否成功的状态码, 成功的个数, 失败的个数, 总数
    let status = con.SUCCESS_STATUS, success = 0, failure = 0, total = len, failureIndex = -1
    for(let i = 0; i < len; i++){
        if (!status) { break }
        let processRes = Dispatch.process(query[i].path, query[i].param)
        if (con.SUCCESS_STATUS === processRes.status) {
            try{
                await Dispatch.post(processRes.res.address, processRes.res.send).then((r) => {
                    arr.push(r.data)
                    if(indexOf(successArr, r.data.status + '') < 0){
                        status = con.ERR_STATUS
                        if (-1 === failureIndex) {
                            failureIndex = i
                        }
                        return
                    }
                    success++
                })
            }catch(e){
                status = con.ERR_STATUS
                if (-1 === failureIndex) {
                    failureIndex = i
                }
                res.json(base.param_err(e, e.message))
            }
        } else {
            status = con.ERR_STATUS
            if (-1 === failureIndex) {
                failureIndex = i
            }
            arr.push(processRes)
            return 
        }
    }
    res.json( {status: status, success: success, failure: total - success, failureIndex: failureIndex, total: total, res: arr} )
}

module.exports = queueQuery